package com.cskaoyan.service;

import com.cskaoyan.bean.Log;
import com.cskaoyan.bean.LogExample;
import com.cskaoyan.mapper.LogMapper;
import com.cskaoyan.vo.BaseRespVo;
import com.cskaoyan.vo.LogVo;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

/**
 * @ description:
 * @ author:台
 **/

@Service
public class LogServiceImpl implements LogService {

    @Autowired
    LogMapper logMapper;

    @Override
    public LogVo logList(Integer page, Integer limit, String sort, String desc, String name) {
        PageHelper.startPage(page, limit);

        LogExample logExample = new LogExample();
        logExample.setOrderByClause("convert(" + sort + " as datetime)" + " " + desc);
        LogExample.Criteria criteria = logExample.createCriteria();
        if (name != null) {
            criteria.andAdminLike("%" + name + "%");
        }
        List<Log> logs = logMapper.selectByExample(logExample);

        PageInfo<Log> logPageInfo = new PageInfo<>(logs);
        long total = logPageInfo.getTotal();

        LogVo logVo = new LogVo();
        logVo.setItems(logs);
        logVo.setTotal(total);
        return logVo;
    }

    @Override
    public int logCreate(HttpServletRequest request, BaseRespVo result) {


        Log log = new Log();
        String requestURI = request.getRequestURI();

        switch (requestURI) {
            case "/admin/auth/login":
                log.setAction("登录");
                break;
            case "/admin/admin/create":
                log.setAction("增加管理员");
                break;
            case "/admin/admin/delete":
                log.setAction("删除管理员");
                break;
            case "/admin/auth/logout":
                log.setAction("退出登录");
                break;
            case "/admin/ad/list":
                log.setAction("大胆的人类竟然在查看广告");
                break;
        }

        String remoteAddr = request.getRemoteAddr();
        Date date = new Date(System.currentTimeMillis());
        date.setHours(date.getHours() + 8);

        log.setType(1);
        log.setStatus(result.getErrno() == 0);
        log.setDeleted(false);
        log.setAddTime(date);
        log.setUpdateTime(date);

        Subject subject = SecurityUtils.getSubject();
        String token = (String) subject.getPrincipal();

        log.setAdmin(token);

        log.setResult(result.getErrmsg());

        log.setIp(remoteAddr);

        if (log.getAction() != null) {
            logMapper.insertSelective(log);
        }

        return 0;
    }
}
